package com.generalbackend.role.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.generalbackend.common.constants.Constants;
import com.generalbackend.role.mapper.PermissionMapper;
import com.generalbackend.role.model.entity.Permission;
import com.generalbackend.common.model.entity.User;
import com.generalbackend.role.model.query.PermissionQuery;
import com.generalbackend.role.service.IPermissionService;
import com.generalbackend.common.util.ClientUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.generalbackend.common.constants.Constants.DATA;
import static com.generalbackend.common.constants.Constants.TOTAL;

/**
* @Description 菜单权限表业务层实现类
* @author tim.xie
* @date 2021-12-10 11:01
*/

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public Boolean insert(Permission permission) {
        // 新增校验
        checkPermission(permission);
        // 填充额外属性
        fillPermission(permission);
        Integer num = permissionMapper.insert(permission);
        if(num <= 0) {
         return false;
         }
		return true;
	}

	@Override
	public Boolean update(Permission permission) {
        // 修改校验
        checkPermission(permission);
        // 填充额外属性
        fillPermission(permission);
        Integer num = permissionMapper.updateById(permission);
        if(num <= 0) {
          return false;
        }
		return true;
	}
    /**
    * 新增或者修改校验
    * @param permission
    * @return
    */
    private void checkPermission(Permission permission) {

    }
    /**
    *填充额外属性
    **/
    private void fillPermission(Permission permission) {

    }

	@Override
	public Boolean deleteById(String id) {
        permissionMapper.deleteById(id);
		return true;
	}

	@Override
	public Permission selectById(String id) {
        Permission permission = permissionMapper.selectById(id);
        return permission;
	}
    @Override
    public JSONObject list(PermissionQuery permissionQuery) {
        JSONObject result = new JSONObject();
        Page<Permission> page = new Page<>(permissionQuery.getOffset(), permissionQuery.getLimit());
        List<Permission> permissionList = permissionMapper.list(page,permissionQuery);
        result.put(TOTAL, page.getTotal());
        result.put(DATA, permissionList);
        return result;
    }

    @Override
    public void updatePermissionTable(List<Permission> permissions) {
        permissionMapper.delete(null);
        saveBatch(permissions);
    }

    @Override
    public List<Permission> allPermission() {
        return permissionMapper.selectList(null);
    }

    @Override
    public JSONArray getPermissionByUserId(Long userId) {
        List<Permission> permissions = permissionMapper.getPermissionByUserId(userId);
        JSONArray menu = new JSONArray();
        if (permissions != null && permissions.size() > 0) {
            menu.addAll(permissions.stream().map(Permission::getId).collect(Collectors.toList()));
            return menu;
        }
        return new JSONArray();
    }

    @Override
    public List<Permission> getPermissionTree() {
        List<Permission> userPermissions = new ArrayList<>();
        User user = ClientUtil.getUser();
        if (user != null) {
            userPermissions = permissionMapper.getPermissionByUserId(user.getId());
            userPermissions = userPermissions.stream()
                    .filter(permission -> permission.getType() != 4)
                    .collect(Collectors.toList()).stream()
                    .sorted(Comparator.comparing(Permission::getSort))
                    .collect(Collectors.toList());
        }
        return fillChildPermission(userPermissions, "0");
    }

    private List<Permission> fillChildPermission(List<Permission> permissionList, String pid) {
        List<Permission> childList = new LinkedList<>();
        Iterator<Permission> iterator = permissionList.iterator();
        while (iterator.hasNext()) {
            Permission next = iterator.next();
            if (StringUtils.equals(next.getParentId(),pid)) {
                childList.add(next);
                next.setSubmenu(fillChildPermission(permissionList, next.getId()));
            }
        }
        return childList;
    }

    @Override
    public List<Permission> getAllPermissionTree() {
        List<Permission> userPermissions = permissionMapper.getPermissionByUserId(Constants.ADMIN_ID);
        userPermissions = userPermissions.stream()
                .filter(permission -> permission.getType() != 4)
                .collect(Collectors.toList()).stream()
                .sorted(Comparator.comparing(Permission::getSort))
                .collect(Collectors.toList());
        return fillChildPermission(userPermissions, "0");
    }

}
